<?php


namespace App\Dao;


use App\Model\CooperativeMenu;
use Hyperf\Database\Model\Builder;

class CooperativeMenuDao extends AbstractDao
{
    public function where(array $where): Builder
    {
        $builder = CooperativeMenu::query();
        foreach ($where as $field => $value) {
            switch ($field) {
                case 'ids':
                    $builder->whereIn('id', $value);
                    break;
                case 'menu_config_ids':
                    $builder->whereIn('menu_config_id', $value);
                    break;
                default:
                    $builder->where($field, $value);
            }
        }
        return $builder;
    }

    public function tree($menus, $pid = 0)
    {
        $tree = [];
        /** @var CooperativeMenu $menu */
        foreach ($menus as $menu) {
            if ($menu->pid == $pid) {
                $node = [];
                $node['id'] = $menu->id;
                $node['name'] = $menu->name;
                $node['title'] = $menu->title;
                $node['api'] = $menu->api;
                $node['type'] = $menu->type;
                $node['pid'] = $pid;
                $children = $this->tree($menus, $menu->menu_config_id);
                if (!empty($children)) {
                    $node['children'] = $children;
                }
                $tree[] = $node;
            }
        }
        return $tree;
    }


}